package zjitc.controller;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;

import com.google.gson.Gson;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.InternalResourceView;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.ScanResult;
import zjitc.po.Book;
import zjitc.po.User;
import zjitc.service.UserService;
import zjitc.utils.RedisConfig;

import java.util.List;

/**
 * Create by IntelliJ IDEA
 *
 * @author: jsonor
 * @date-Time: 2018/4/12 16:56
 * @description:
 */
@Controller
@RequestMapping("/user")
public class UserController {
  private View view;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisConfig redisConfig;

    @RequestMapping("/showUserList")
   public ModelAndView showUserList()
    {
      List<User> list= userService.findAllUser();
        if(!redisConfig.exists("userId")||!redisConfig.exists("uid")) {
           for(User user:list)
           {
               redisConfig.sadd("userId",  "userId",  "{\"uid\":"+user.getUid()+",\"username\":"+"\""+user.getUsername()+"\""+",\"password\":"+"\""+user.getPassword()+"\""+",\"email\":"+"\""+user.getEmail()+"\""+",\"phone\":"+"\""+user.getPhone()+"\""+",\"addr\":"+"\""+user.getAddr()+"}");
           }
        }
      else
        {
          Jedis jedis=new Jedis();
          ScanResult<String> userId = jedis.sscan("userId", 0);
          List<String> result = userId.getResult();
          Iterator<String> iterator = result.iterator();
          while (iterator.hasNext())
          {
            String next = iterator.next();
            Gson gson=new Gson();
            User user = gson.fromJson(next, User.class);
          }
        }
        ModelAndView modelAndView=new ModelAndView();
      modelAndView.setView(new InternalResourceView("/WEB-INF/admin/user/list.jsp"));
      modelAndView.addObject("list",list);
      return modelAndView;
    }
    @RequestMapping("/deleteUserByUid")
    public View deleteUserByUid(HttpServletRequest request)
    {
      String uid = request.getParameter("uid");
      if(redisConfig.sismember("uid",uid))
      {
        Integer id = Integer.valueOf(uid);
       int num= userService.deleteUserByUid(id);
      }
      else
      {
         redisConfig.srem("uid",uid);
        Integer id = Integer.valueOf(uid);
        int num= userService.deleteUserByUid(id);
      }
      view=new InternalResourceView("/app/user/showUserList");
      return view;
    }
    @RequestMapping("/userLoginUI")
  public String userLoginUI()
    {
      return "bookPage/login";
    }
  @RequestMapping("/userLogin")
  public ModelAndView userLogin(HttpServletRequest request,HttpSession session,String username,String password)
  {
     ModelAndView view=new ModelAndView();
    String inputCode = request.getParameter("code");
    String trueCode = (String) request.getSession().getAttribute("validatecode");
    if(!inputCode.equalsIgnoreCase(trueCode))
    {
      view.addObject("codeMsg","验证码错误");
      view.setView(new InternalResourceView("/WEB-INF/bookPage/login.jsp"));
      return view;
    }
    username=request.getParameter("username");
    password=request.getParameter("password");
    User user=userService.userLogin(username,password);
    if(user!=null)
    {
      session.setAttribute("username",user.getUsername());
      view.setView(new InternalResourceView("/app/category/index"));
      return view;
    }
      view.addObject("msg","用户名或密码错误");
      view.setView(new InternalResourceView( "/WEB-INF/bookPage/login.jsp"));
      return view;
  }
  @RequestMapping("/removeUser")
  public View removeUser(HttpSession session)
  {
    session.removeAttribute("username");
    View view=new InternalResourceView("/app/category/index");
    return view;
  }
  @RequestMapping("/userRegisterUI")
  public String userRegisterUI()
  {
    return "bookPage/regist";
  }
  @RequestMapping("/findByUsername")
  public String findByUsername(HttpServletRequest request,HttpServletResponse response)
      throws IOException {
   String username= request.getParameter("username");
   User user=userService.findByUsername(username);
    if (user==null){
      response.getWriter().print(true);
    }else {
      response.getWriter().print(false);
    }
    return null;
  }
    @RequestMapping("/userRegister")
    public String userRegister(HttpServletRequest request,Model model)
    {
      String inputCode = request.getParameter("code");
      String trueCode = (String) request.getSession().getAttribute("validatecode");
      if(!inputCode.equalsIgnoreCase(trueCode))
      {
        model.addAttribute("codeMsg","验证码错误");
        return "bookPage/regist";
      }
        User user=new User();
        try {
            BeanUtils.populate(user,request.getParameterMap());
            int num= userService.addUser(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "bookPage/login";
    }
}
